﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IoTCM
{
    public class DataItemCollection : IEnumerable<DataItem>
    {
        private object m_syncRoot;
        private Dictionary<string, DataItem> m_items;
        private Thing m_parent;

        internal DataItemCollection(Thing parent)
        {
            m_parent = parent;

            // data item ID is case-insensitive
            m_items = new Dictionary<string, DataItem>(StringComparer.InvariantCultureIgnoreCase);
            m_syncRoot = new object();
        }

        public DataItem Add(DataItem item)
        {
            if(item == null) throw new ArgumentNullException();

            lock (m_syncRoot)
            {
                if (m_items.ContainsKey(item.ID))
                {
                    throw new ArgumentException(string.Format("DataItem with ID '{0}' already in collection", item.ID));
                }

                // TODO: look for ID duplication in children

                m_items.Add(item.ID, item);
            }

            return item;
        }

        public int Count
        {
            get { return m_items.Count; }
        }

        public DataItem this[string itemID]
        {
            get 
            {
                if (string.IsNullOrEmpty(itemID))
                {
                    throw new ArgumentException("itemID is required");
                }

                if (!m_items.ContainsKey(itemID))
                {
                    return null;
                }

                return m_items[itemID]; 
            }
        }

        public void AddRange(IEnumerable<DataItem> items)
        {
            if (items == null) throw new ArgumentNullException();

            foreach (var thing in items)
            {
                Add(thing);
            }
        }

        public IEnumerator<DataItem> GetEnumerator()
        {
            lock (m_syncRoot)
            {
                return m_items.Values.GetEnumerator();
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
        /*
        public DataItem Item(string itemID)
        {
            lock (m_syncRoot)
            {
                if (!m_items.ContainsKey(itemID))
                {
                    return null;
                }

                return m_items[itemID];
            }
        }
        */
    }
}
